package com.bookcloud.java21.chapter7.异常捕获72;

/** 异常捕获 */
public class ExceptionCatching {
  public static void main(String[] args) {
    // 一个catch语句
    try {
      int[] arr = {1, 2, 3};
      System.out.println(arr[3]);
    } catch (ArrayIndexOutOfBoundsException e) {
      System.out.println("数组索引越界");
      // e.printStackTrace();
    }
    System.out.println(" 代码执行完毕 （1）");
    // 多个catch语句
    System.out.println("=======演示多个catch语句======");
    try {
      String str = null;
      System.out.println(str.length());
      int[] arr = {1, 2, 3};
      System.out.println(arr[3]);
    } catch (ArrayIndexOutOfBoundsException e) {
      System.out.println("数组索引越界");
      e.printStackTrace();
    } catch (NullPointerException e) {
      System.out.println("空指针异常");
      e.printStackTrace();
    } catch (Exception e) {
      System.out.println("其他异常");
      e.printStackTrace();
    }
    //  一个catch块捕获多种异常（Java 7+）
    System.out.println("=======演示一个catch块捕获多种异常======");
    try {
      String str = null;
      System.out.println(str.length());
      int[] arr = {1, 2, 3};
      System.out.println(arr[3]);
    } catch (ArrayIndexOutOfBoundsException | NullPointerException e) {
      System.out.println("数组索引越界或空指针异常");
      e.printStackTrace();
    }
    // 打印出异常的详细信息
    System.out.println("=======演示打印出异常的详细信息======");
    try {
      String str = null;
      System.out.println(str.length());
      int[] arr = {1, 2, 3};
      System.out.println(arr[3]);
    } catch (ArrayIndexOutOfBoundsException | NullPointerException e) {
      System.out.println("数组索引越界或空指针异常");
      System.out.println("e.getMessage() = " + e.getMessage());
      System.out.println("e.toString() = " + e.toString());
      System.out.println("e.getCause() = " + e.getCause());
      System.out.println("============ e:" + e);
      e.printStackTrace();
    }
  }
}
